from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from .config import Config

db = SQLAlchemy()
login_manager = LoginManager()

def create_app():
    app = Flask(__name__,
                template_folder='templates',
                static_folder='static')
    
    app.config.from_object(Config)
    
    # 确保设置了 SECRET_KEY
    if not app.config.get('SECRET_KEY'):
        app.config['SECRET_KEY'] = 'dev'
    
    db.init_app(app)
    
    # 初始化 Flask-Login
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    login_manager.login_message = '请先登录'
    login_manager.login_message_category = 'info'
    
    # 确保导入所有模型
    from .models import User, Sample  # 添加 Sample
    
    # 注册蓝图
    from .routes import main, auth, data, analysis, reports
    app.register_blueprint(main.bp)
    app.register_blueprint(auth.bp)
    app.register_blueprint(data.bp)
    app.register_blueprint(analysis.bp)
    app.register_blueprint(reports.bp)
    
    return app
